package com.google.code.virtualhockey.vhx.server.servlet.custom

import com.google.code.virtualhockey.vhx.server.servlet.rpc.TSecurityTokenChecker
import javax.servlet.http.HttpServletRequest
import com.google.code.virtualhockey.vhx.shared.VhxSharedUtils
import com.google.code.virtualhockey.vhx.shared.error.{WebInvalidSessionException, WebSecurityException}

/**
 * Verifies the security token based on the GAE session cookie.
 */
object VhxSecurityTokenChecker extends TSecurityTokenChecker {
  def checkSecurityToken( strClientToken: String, rq: HttpServletRequest ) {

    // if we are running locally, let's assume everything is right
    //
    if ( rq.getServerName == "localhost" )
      return

    // if we have no client session, something is wrong as the user should be identified
    //
    if ( strClientToken == null )
      throw new WebInvalidSessionException( "No client token available." )

    val optGaeCookie = rq.getCookies.find( _.getName == VhxSharedUtils.SESSION_COOKIE )

    if ( optGaeCookie == None )
      throw new WebInvalidSessionException( "No session cookie found." )

    if ( optGaeCookie.get.getValue != strClientToken )
      throw new WebInvalidSessionException( "Security token validation failed." )
  }
}
